package com.example.pfe_copie_finale;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Chiffreaffaire extends Activity {
	
	// Progress Dialog
    private ProgressDialog pDialog;
    
 // Creating JSON Parser object
    jsonParser jParser = new jsonParser();
 
    ArrayList<HashMap<String, String>> caisseList;
 
    // url to get all products list
    private static String url_all_caisses = "http://10.0.2.2/getAllCaisse";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_caisse = "caisses";
    private static final String TAG_PID = "id";
    private static final String TAG_NAME = "libelle";
    private List<String> array_spinner=new ArrayList<String>();
 
    // products JSONArray
    JSONArray caisses = null;
    
	private EditText pickDate;
	private EditText pickDate1;
	private Spinner spinner;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mYear1;
	private int mMonth1;
	private int mDay1;
	static final int DATE_DIALOG_ID1 = 1;
	static final int DATE_DIALOG_ID2 = 2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chiffreaffaire);
		pickDate = (EditText) findViewById(R.id.editText1);
		pickDate1 = (EditText) findViewById(R.id.editText2);
		spinner = (Spinner) findViewById(R.id.spinner1);
		Button valider= (Button) findViewById(R.id.valider);
		valider.setOnClickListener(new View.OnClickListener() {
			 
	        @Override
	        public void onClick(View view) {
	            // Launching All products Activity
	            Intent i = new Intent(getApplicationContext(), Tablechiffre.class);
	            startActivity(i);

	        }
	    });
		
		
		
		pickDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
			showDialog(DATE_DIALOG_ID1);
			}
			});
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			updateDisplay(DATE_DIALOG_ID1);
			
		
		
		pickDate1.setOnClickListener(new View.OnClickListener() {

		public void onClick(View v) {
		showDialog(DATE_DIALOG_ID2);
		}
		});
		final Calendar c1 = Calendar.getInstance();
		mYear1 = c1.get(Calendar.YEAR);
		mMonth1 = c1.get(Calendar.MONTH);

		mDay1 = c1.get(Calendar.DAY_OF_MONTH);
		updateDisplay(DATE_DIALOG_ID2);
		
		
		
		
		
		
		// Hashmap for ListView
       caisseList = new ArrayList<HashMap<String, String>>();
       // Loading products in Background Thread
      
        new LoadCaisses().execute();
        array_spinner.add("choisir caisse");
        ArrayAdapter adapter = new ArrayAdapter(Chiffreaffaire.this,android.R.layout.simple_spinner_item, array_spinner);
        spinner.setAdapter(adapter);
        
        
        
 
//         //Get listview
//        ListView lv = getListView();
// 
//        // on seleting single product
//        // launching Edit Product Screen
//        lv.setOnItemClickListener(new OnItemClickListener() {
// 
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                    int position, long id) {
//                // getting values from selected ListItem
//               String pid = ((TextView) view.findViewById(R.id.pid)).getText()
//                        .toString();
 
//                // Starting new intent
//                Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
//                // sending pid to next activity
//                in.putExtra(TAG_PID, pid);
// 
//                // starting new activity and expecting some response back
//                startActivityForResult(in, 100);
            }
//        });
		
//	}
	
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID1:
		    return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
		case DATE_DIALOG_ID2:
			return new DatePickerDialog(this,mDateSetListener1,mYear1, mMonth1, mDay1);
		}
		return null;
		}
		protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID1 :
		((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);break;

		case DATE_DIALOG_ID2:
			((DatePickerDialog) dialog).updateDate(mYear1, mMonth1, mDay1);break;

		}
		} 
		private void updateDisplay(int id) {
			switch (id) {
			case DATE_DIALOG_ID1 :
				pickDate.setText(
						new StringBuilder()
						// Month is 0 based so add 1
						.append(mDay ).append("-")
						.append(mMonth+1).append("-")
						.append(mYear).append(" "));
			case DATE_DIALOG_ID2:
				pickDate1.setText(
						new StringBuilder()
						 // Month is 0 based so add 1
						.append(mDay1 ).append("-")
						.append(mMonth1+1).append("-")
						.append(mYear1).append(" "));
			}
		
		
		}
		
		private DatePickerDialog.OnDateSetListener mDateSetListener =new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
		mYear = year;
		mMonth = monthOfYear;
		mDay = dayOfMonth;
		updateDisplay(1);
		}


		};
		private DatePickerDialog.OnDateSetListener mDateSetListener1 =new DatePickerDialog.OnDateSetListener() {

			public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
			mYear1 = year;
			mMonth1 = monthOfYear;
			mDay1 = dayOfMonth;
			updateDisplay(2);
			}


			};
			
			
			
			
			
			
public class LoadCaisses extends AsyncTask<String, String, String> {
		    	
		        @Override
		        protected void onPreExecute() {
		        	super.onPreExecute();
		            pDialog = new ProgressDialog(Chiffreaffaire.this);
		            pDialog.setMessage("Loading caisses. Please wait...");
		            pDialog.setIndeterminate(false);
		            pDialog.setCancelable(true);
		            pDialog.show();
		        }
		        /**
		         * getting All products from url
		         * */
		        protected String doInBackground(String... arg0) {
					// Building Parameters
		            List<NameValuePair> params = new ArrayList<NameValuePair>();
		            // getting JSON string from URL
		            JSONObject json = jParser.makeHttpRequest(url_all_caisses, "GET", params);
		 
		            // Check your log cat for JSON reponse
		            Log.d("All Products: ", json.toString());
		            
		            // dismiss the dialog after getting all products
		            try {
		                // Checking for SUCCESS TAG
		                int success = json.getInt(TAG_SUCCESS);
					if (success == 1) {
                        // products found
                        // Getting Array of Products
                        caisses = json.getJSONArray(TAG_caisse);
                        Log.d("aa: ", "qq");
                        // looping through All Products
                        for (int i = 0; i < caisses.length(); i++) {
                            JSONObject c = caisses.getJSONObject(i);
     
                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);
                            Log.d("aa: ", name);
                        	array_spinner.add(name);
                        	
     
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
     
                            // adding each child node to HashMap key => value
                            map.put(TAG_PID, id);
                            map.put(TAG_NAME, name);
     
                            // adding HashList to ArrayList
                            caisseList.add(map);
                        }
                       
                    }
                	
                		}
		            catch (JSONException e) {
		                e.printStackTrace();
		            }
		            Log.d("aa: ", "ww");
		            return null;
		        }
		        /**
		         * After completing background task Dismiss the progress dialog
		         * **/
		        protected void onPostExecute(String file_url) {
		            // dismiss the dialog after getting all products
		            pDialog.dismiss();
		            
		            // updating UI from Background Thread
		            runOnUiThread(new Runnable() {
		                public void run() {
		                    /**
		                     * Updating parsed JSON data into ListView
		                     * */
//		                	ListAdapter adapter = new SimpleAdapter(
//		                            Chiffreaffaire.this, productsList,
//		                            R.layout.list_item, new String[] { TAG_PID,
//		                                    TAG_NAME},
//		                            new int[] { R.id.pid, R.id.name });
//		                    // updating listview
//		                    setListAdapter(adapter);
		                 
		        }
		            });
		            }
}
}
		        
		            
		                
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
		        
	

